package com.jike.noobmoney.mvp.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.lz.playmy.WowanIndex;
import com.toomee.mengplus.manager.TooMeeManager;
import com.jike.noobmoney.R;
import com.jike.noobmoney.mvp.view.activity.MainActivity;
import com.jike.noobmoney.mvp.view.activity.MyEventActivity;
import com.jike.noobmoney.adapter.TaskListAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.TaskListEntity;
import com.jike.noobmoney.entity.UserInfoEntity;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by kekex on 2018/8/21.
 * Home
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.cardview_yaoqing)
    CardView cardviewYaoqing;
    @BindView(R.id.cardview_kuaisu)
    CardView cardviewKuaisu;
    @BindView(R.id.cardview_gaoe)
    CardView cardviewGaoe;
    @BindView(R.id.cardview_xingyun)
    CardView cardviewXingyun;
    @BindView(R.id.cardview_qq)
    CardView cardviewQq;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_name)
    TextView tvName;

    private TaskListAdapter adapter;
    private Call<TaskListEntity> taskListCall;
    private List<TaskListEntity.TaskBean> mData = new ArrayList<>();
    private Call<UserInfoEntity> userInfoCall;


    @Override
    protected int layoutResID() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        adapter = new TaskListAdapter(context);
        recyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerview.setAdapter(adapter);
        recyclerview.setNestedScrollingEnabled(false);
        adapter.setOnItemClickListener((adapterView, view, position, l) -> {
            TaskListEntity.TaskBean item = (TaskListEntity.TaskBean) adapter.getItem(position);
            String url = ConstantValue.TaskDetail + item.getT_id();
            startActivity(new Intent(context, MyEventActivity.class).putExtra(MyEventActivity.BUNDLE_KEY_URL, url));
        });
        //getData();


    }

    /**
     * 获取任务列表
     */
    private void getData() {

        String userid = SPUtils.getInstance().getString("userid");
        userInfoCall = RetrofitHelper.getInstance().getUserInfo(userid);
        userInfoCall.enqueue(new Callback<UserInfoEntity>() {
            @Override
            public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
                if (response != null) {
                    UserInfoEntity body = response.body();
                    if (body != null) {
                        UserInfoEntity.UserBean user = body.getUser();
                        if (user != null) {
                            tvName.setText(user.getNick());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfoEntity> call, Throwable t) {

            }
        });


        taskListCall = RetrofitHelper.getInstance().getTaskList();
        taskListCall.enqueue(new Callback<TaskListEntity>() {
            @Override
            public void onResponse(Call<TaskListEntity> call, Response<TaskListEntity> response) {
                if (response != null) {
                    TaskListEntity body = response.body();
                    if (body != null) {
                        if (body.getCode().equals("100")) {
                            List<TaskListEntity.TaskBean> task = body.getTask();
                            if (task != null && task.size() > 0) {
                                mData.clear();
                                mData.addAll(task);
                            }
                            adapter.refresh(mData);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<TaskListEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
            }
        });

    }


    /**
     * 刷新
     */
    public void loadData() {

    }

    @OnClick({R.id.cardview_yaoqing, R.id.cardview_kuaisu, R.id.btn_kuaisu, R.id.cardview_gaoe, R.id.cardview_xingyun, R.id.cardview_qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cardview_yaoqing:
                //邀请
                MainActivity activity = (MainActivity) getActivity();
                if (activity != null) {
                    activity.goRecommend(3);
                }
                break;
            case R.id.cardview_kuaisu:
            case R.id.btn_kuaisu:
                //快速任务
                Intent intent = new Intent();
                intent.setClass(context, WowanIndex.class);
                startActivity(intent);
                break;
            case R.id.cardview_gaoe:
                //高额任务
                TooMeeManager.start(context);
                break;
            case R.id.cardview_xingyun:
                //幸运
                String url = "http://engine.liulianqc.com/index/activity?appKey=ZgzfvSPbz5aG1JE1qsTrCeXWXyd&adslotId=485";
                startActivity(new Intent(context, MyEventActivity.class).putExtra(MyEventActivity.BUNDLE_KEY_URL, url));
                break;
            case R.id.cardview_qq:
                //QQ群
                startQQ(context, 3, "564104407");
                break;
        }
    }

    /**
     * @param mContext 上下文
     * @param type     类型  1.QQ聊天   2.QQ资料界面   3.QQ群资料界面
     * @param qqnum    QQ号
     */
    public void startQQ(Context mContext, int type, String qqnum) {
        if (checkApkExist(mContext, "com.tencent.mobileqq")) {
            String url = "";
            switch (type) {
                case 1:
                    url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qqnum;
                    break;
                case 2:
                    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                            + "&card_type=person&source=qrcode";
                    break;
                case 3:
                    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                            + "&card_type=group&source=qrcode";
                    break;
                default:
                    break;
            }
            mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } else {
            ToastUtils.showLongToast("本机未安装QQ应用");
        }
    }

    /**
     * 检查是否安装QQ
     */
    public boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
